# intlagrande.R
# interpolador de Lagrange
# http://pt.wikipedia.org/wiki/Polin%C3%B4mio_de_Lagrange

# exemplo de uso:
# source('intlagrange.R')
# intlagrange(c(1,2,3,4), c(2,3,4,5))
# (intlagrange(c(1,2,3,4), c(2,3,4,5)))(1)

intlagrange <- function(xs, ys)
	function(x) {
		k <- length(xs)
		y <- 0
		for(j in 1:k) {
			t <- rep(1, k)
			for(i in 1:k)
				if(j != i)
					t[i] <- (x - xs[i])/(xs[j]-xs[i])
			y <- y + (ys[j] * prod(t))
		}
		y
	}

# para funcionar para vectores, e cortar janela

cut_lagrange <- function(xs, ys, min, max)
	function(x) {
		fn <- intlagrange(xs,ys)
		y <- rep(0, length(x))
		for(i in 1:length(x))
			if(min <= x[i] && x[i] <= max) {
				y[i] <- fn(x[i])
				if(y[i] < 0)  # dont let it go below zero
					y[i] <- 0
			}
		y
	}

